package com.example.demo.utils;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Json字符串与类的互相转换
 */
public class JsonUtil {
    //用于转换的对象
    private static ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 实体类转换为json对象字符串
     * @param object
     * @return
     */
    public static String toJsonString(Object object){
        try{
          return MAPPER.writeValueAsString(object);
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Json字符串转换为对象
     * @param jsonString
     * @param beanType
     * @return
     * @param <T>
     */
    public static <T> T toObject(String jsonString, Class<T> beanType){
        try{
            return MAPPER.readValue(jsonString,beanType);
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
